<template>
    <div class="main-container">
        <!-- 左侧监控检测数据 -->
        <div class="monitor-section">
            <h2 class="section-title">实时监控检测数据</h2>
            <div v-if="monitorSessions.slice(-5).length > 0" class="data-container">
                <div v-for="(session, index) in monitorSessions.slice(-5)" :key="session.id" class="session-card">
                    <div class="session-header">
                        <div class="session-title">
                            <div class="session-number">{{ index + 1 }}</div>
                            <div class="session-info">
                                <h3>第{{ index + 1 }}批次</h3>
                                <div class="time-info">
                                    <span>开始时间: {{ session.start_time }}</span>
                                    <span>结束时间: {{ session.end_time || '进行中' }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="time-slots">
                        <div v-for="(slot, slotIndex) in session.time_slots" 
                             :key="slotIndex" 
                             class="time-slot-card"
                             @click="showDetailDialog(session, slot)">
                            <div class="time-range">
                                {{ formatTime(slot.start_time) }} - {{ formatTime(slot.end_time) }}
                            </div>
                            <div class="detection-summary">
                                <div v-for="(count, className) in slot.detection_counts" 
                                     :key="className" 
                                     class="detection-item">
                                    <span class="class-name">{{ className }}</span>
                                    <span class="count">{{ count }}次</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <el-empty v-else></el-empty>
        </div>

        <!-- 右侧视频检测数据 -->
        <div class="video-section">
            <h2 class="section-title">视频检测数据</h2>
            <div v-if="videoSessions.slice(-5).length > 0" class="data-container">
                <div v-for="(video, index) in videoSessions.slice(-5)" :key="video.id" class="session-card">
                    <div class="session-header">
                        <div class="session-title">
                            <div class="session-number">{{ index + 1 }}</div>
                            <div class="session-info">
                                <h3>第{{ index + 1 }}个视频</h3>
                                <div class="time-info">
                                    <span>上传时间: {{ video.uploaded_at }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="time-slots">
                        <div v-for="(slot, slotIndex) in video.time_slots" 
                             :key="slotIndex" 
                             class="time-slot-card"
                             @click="showDetailDialog(video, slot)">
                            <div class="time-range">
                                {{ formatVideoTime(slot.start_time) }} - {{ formatVideoTime(slot.end_time) }}
                            </div>
                            <div class="detection-summary">
                                <div v-for="(count, className) in slot.detection_counts" 
                                     :key="className" 
                                     class="detection-item">
                                    <span class="class-name">{{ className }}</span>
                                    <span class="count">{{ count }}次</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <el-empty v-else></el-empty>
        </div>

        <!-- 详细数据弹窗 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="90%"
            :modal-append-to-body="false"
            :append-to-body="true"
            custom-class="detection-dialog">
            <div class="detail-content">
                <div class="detail-layout">
                    <!-- 左侧表格区域 -->
                    <div class="table-section">
                        <div class="statistics-section">
                            <h4>统计概览</h4>
                            <div class="statistics-grid">
                                <div class="stat-item">
                                    <span class="label">总检测次数：</span>
                                    <span class="value">{{ currentDetails.length }}</span>
                                </div>
                                <div class="stat-item">
                                    <span class="label">检测类别：</span>
                                    <span class="value">{{ Object.keys(currentClassStats).length }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="details-section">
                            <h4>检测详情</h4>
                            <el-table :data="currentDetails" style="width: 100%" border>
                                <el-table-column prop="class_name" label="检测物体" width="120"></el-table-column>
                                <el-table-column prop="start_time" label="开始时间" width="180">
                                    <template slot-scope="scope">
                                        {{ isVideoData ? formatVideoTime(scope.row.start_time) : formatTime(scope.row.start_time) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="end_time" label="结束时间" width="180">
                                    <template slot-scope="scope">
                                        {{ isVideoData ? formatVideoTime(scope.row.end_time) : formatTime(scope.row.end_time) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="confidence" label="置信度" width="120">
                                    <template slot-scope="scope">
                                        {{ (scope.row.confidence * 100).toFixed(2) }}%
                                    </template>
                                </el-table-column>
                                <el-table-column prop="created_at" label="创建时间" width="180"></el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 右侧图表区域 -->
                    <div class="charts-section">
                        <div ref="pieChart" class="chart-item"></div>
                        <div ref="barChart" class="chart-item"></div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getRealtimeData, getVideoData } from '@/api/data';
import * as echarts from 'echarts';

export default {
    data() {
        return {
            monitorSessions: [], // 存储实时监控数据
            videoSessions: [], // 存储视频检测数据
            intervalId: null, // 定时器ID
            dialogVisible: false, // 弹窗显示状态
            currentDetails: [], // 当前显示的详细数据
            dialogTitle: '', // 弹窗标题
            timeSlotDuration: 30, // 时间段长度（秒）
            isVideoData: false, // 当前是否为视频数据
            pieChart: null, // 饼图实例
            barChart: null, // 柱状图实例
            resizeObserver: null, // ResizeObserver实例
        };
    },
    computed: {
        currentClassStats() {
            const stats = {};
            this.currentDetails.forEach(detail => {
                const className = detail.class_name;
                stats[className] = (stats[className] || 0) + 1;
            });
            return stats;
        }
    },
    mounted() {
        this.fetchData();
        this.intervalId = setInterval(this.fetchData, 1800000);
    },
    beforeDestroy() {
        clearInterval(this.intervalId);
        this.cleanupCharts();
    },
    methods: {
        async fetchData() {
            try {
                // 获取实时监控数据
                const monitorResponse = await getRealtimeData();
                if (monitorResponse && monitorResponse.code === 1) {
                    this.monitorSessions = this.processTimeSlots(monitorResponse.data.sessions);
                } else {
                    this.$message.error((monitorResponse && monitorResponse.msg) || '获取实时监控数据失败');
                }

                // 获取视频检测数据
                const videoResponse = await getVideoData();
                if (videoResponse && videoResponse.code === 1) {
                    this.videoSessions = this.processVideoData(videoResponse.data.videos);
                } else {
                    this.$message.error((videoResponse && videoResponse.msg) || '获取视频检测数据失败');
                }
            } catch (error) {
                console.error('Error fetching data:', error);
                this.$message.error('获取数据失败');
            }
        },

        // 处理实时监控数据的时间段
        processTimeSlots(sessions) {
            if (!sessions || !Array.isArray(sessions)) return [];
            
            return sessions.map(session => {
                const timeSlots = [];
                const details = session.detection_details || [];
                
                if (details.length === 0) return { ...session, time_slots: [] };

                // 获取会话开始时间
                const sessionStartTime = new Date(session.start_time).getTime();
                
                // 按时间段分组
                details.forEach(detail => {
                    const startTime = new Date(detail.start_time).getTime();
                    // 计算相对于会话开始时间的时间段索引
                    const relativeTime = startTime - sessionStartTime;
                    const slotIndex = Math.floor(relativeTime / (this.timeSlotDuration * 1000));
                    
                    if (!timeSlots[slotIndex]) {
                        timeSlots[slotIndex] = {
                            start_time: new Date(sessionStartTime + slotIndex * this.timeSlotDuration * 1000),
                            end_time: new Date(sessionStartTime + (slotIndex + 1) * this.timeSlotDuration * 1000),
                            detection_counts: {},
                            details: []
                        };
                    }
                    
                    // 更新检测计数
                    const className = detail.class_name;
                    timeSlots[slotIndex].detection_counts[className] = 
                        (timeSlots[slotIndex].detection_counts[className] || 0) + 1;
                    
                    // 保存详细数据
                    timeSlots[slotIndex].details.push(detail);
                });

                return {
                    ...session,
                    time_slots: timeSlots.filter(slot => slot !== undefined)
                };
            });
        },

        // 处理视频检测数据
        processVideoData(videos) {
            if (!videos || !Array.isArray(videos)) return [];
            
            return videos.map(video => {
                const timeSlots = [];
                const details = video.detection_details || [];
                
                if (details.length === 0) return { ...video, time_slots: [] };

                // 按视频时长每30秒分组
                details.forEach(detail => {
                    // 使用视频时间戳作为时间段索引
                    const videoTime = detail.video_timestamp || 0;
                    const slotIndex = Math.floor(videoTime / this.timeSlotDuration);
                    
                    if (!timeSlots[slotIndex]) {
                        timeSlots[slotIndex] = {
                            start_time: slotIndex * this.timeSlotDuration,
                            end_time: (slotIndex + 1) * this.timeSlotDuration,
                            detection_counts: {},
                            details: []
                        };
                    }
                    
                    // 更新检测计数
                    const className = detail.class_name;
                    timeSlots[slotIndex].detection_counts[className] = 
                        (timeSlots[slotIndex].detection_counts[className] || 0) + 1;
                    
                    // 保存详细数据
                    timeSlots[slotIndex].details.push(detail);
                });

                return {
                    ...video,
                    time_slots: timeSlots.filter(slot => slot !== undefined)
                };
            });
        },

        // 格式化会话ID
        formatSessionId(sessionId) {
            if (!sessionId) return '未知会话';
            // 取前8位和后4位，中间用...代替
            return `${sessionId.slice(0, 8)}...${sessionId.slice(-4)}`;
        },

        // 格式化视频名称
        formatVideoName(videoName) {
            if (!videoName) return '未命名视频';
            // 如果是UUID格式的文件名，返回更友好的显示
            if (videoName.match(/^[0-9a-f]{32}\.mp4$/i)) {
                return '视频 ' + videoName.slice(0, 8);
            }
            // 如果是普通文件名，去掉扩展名
            return videoName.replace(/\.[^/.]+$/, '');
        },

        // 显示详细数据弹窗
        showDetailDialog(session, slot) {
            const isVideo = !session.session_id;
            this.isVideoData = isVideo;
            let title = '';
            if (isVideo) {
                const idx = this.videoSessions.findIndex(v => v === session);
                title = `第${idx + 1}个视频`;
            } else {
                const idx = this.monitorSessions.findIndex(s => s === session);
                title = `第${idx + 1}批次`;
            }
            this.dialogTitle = `${title} - ${isVideo ? 
                this.formatVideoTime(slot.start_time) : 
                this.formatTime(slot.start_time)} 至 ${isVideo ? 
                this.formatVideoTime(slot.end_time) : 
                this.formatTime(slot.end_time)}`;
            this.currentDetails = slot.details;
            this.dialogVisible = true;
            this.$nextTick(() => {
                this.initCharts();
            });
        },

        // 关闭弹窗
        handleDialogClose() {
            this.dialogVisible = false;
            this.currentDetails = [];
            this.isVideoData = false;
        },

        // 格式化时间
        formatTime(date) {
            if (!(date instanceof Date)) {
                date = new Date(date);
            }
            return date.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        },

        // 格式化视频时间
        formatVideoTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        },

        initCharts() {
            if (!this.$refs.pieChart || !this.$refs.barChart) return;

            const data = Object.entries(this.currentClassStats).map(([name, value]) => ({
                name,
                value
            }));

            // 清理旧的图表实例
            this.cleanupCharts();

            // 初始化饼图
            this.pieChart = echarts.init(this.$refs.pieChart);
            this.pieChart.setOption({
                title: {
                    text: '检测物体分布',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: data.map(item => item.name)
                },
                series: [{
                    name: '检测数量',
                    type: 'pie',
                    radius: '50%',
                    data: data,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            });

            // 初始化柱状图
            this.barChart = echarts.init(this.$refs.barChart);
            this.barChart.setOption({
                title: {
                    text: '检测物体数量统计',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                xAxis: {
                    type: 'category',
                    data: data.map(item => item.name),
                    axisLabel: {
                        interval: 0,
                        rotate: 30
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '检测次数',
                    minInterval: 1,
                    min: 0,
                    max: Math.max(6, Math.max(...data.map(item => item.value))),
                    splitLine: {
                        show: true,
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [{
                    name: '检测次数',
                    type: 'bar',
                    data: data.map(item => item.value),
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 0.5, color: '#188df0' },
                            { offset: 1, color: '#188df0' }
                        ])
                    }
                }]
            });

            // 使用 ResizeObserver 监听容器大小变化
            if (this.resizeObserver) {
                this.resizeObserver.disconnect();
            }
            this.resizeObserver = new ResizeObserver(() => {
                this.pieChart && this.pieChart.resize();
                this.barChart && this.barChart.resize();
            });
            this.resizeObserver.observe(this.$refs.pieChart);
            this.resizeObserver.observe(this.$refs.barChart);
        },

        cleanupCharts() {
            if (this.pieChart) {
                this.pieChart.dispose();
                this.pieChart = null;
            }
            if (this.barChart) {
                this.barChart.dispose();
                this.barChart = null;
            }
            if (this.resizeObserver) {
                this.resizeObserver.disconnect();
                this.resizeObserver = null;
            }
        }
    },
    watch: {
        dialogVisible(newVal) {
            if (!newVal) {
                this.cleanupCharts();
            }
        }
    }
};
</script>

<style scoped>
.main-container {
    display: flex;
    gap: 24px;
    padding: 24px;
    background-color: #f5f7fa;
    height: calc(100vh - 84px);
    overflow: hidden;
}

.monitor-section,
.video-section {
    flex: 1;
    background: #fff;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.08);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.section-title {
    margin: 0 0 24px 0;
    padding-bottom: 16px;
    border-bottom: 2px solid #EBEEF5;
    color: #303133;
    font-size: 20px;
    font-weight: 600;
}

.data-container {
    display: flex;
    flex-direction: column;
    gap: 24px;
    overflow-y: auto;
    flex: 1;
    padding-right: 12px;
    max-height: calc(100vh - 200px);
}

.session-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
    padding: 20px;
    transition: all 0.3s ease;
    margin-bottom: 16px;
}

.session-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}

.session-header {
    margin-bottom: 20px;
}

.session-title {
    display: flex;
    gap: 16px;
    align-items: flex-start;
}

.session-number {
    background: linear-gradient(135deg, #409EFF, #36D1DC);
    color: white;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(64,158,255,0.3);
}

.session-info {
    flex: 1;
}

.session-info h3 {
    margin: 0 0 8px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
}

.time-info {
    color: #909399;
    font-size: 14px;
    display: flex;
    gap: 16px;
}

.time-slots {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.time-slot-card {
    background: #f8f9fb;
    border-radius: 8px;
    padding: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    border: 1px solid #EBEEF5;
}

.time-slot-card:hover {
    background: #f0f2f5;
    border-color: #DCDFE6;
}

.time-range {
    font-size: 14px;
    color: #606266;
    margin-bottom: 12px;
    font-weight: 500;
}

.detection-summary {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.detection-item {
    background: #fff;
    padding: 6px 12px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    gap: 8px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.04);
    border: 1px solid #EBEEF5;
}

.class-name {
    color: #303133;
    font-weight: 500;
}

.count {
    color: #409EFF;
    font-weight: 600;
}

/* 自定义滚动条样式 */
.data-container::-webkit-scrollbar {
    width: 6px;
}

.data-container::-webkit-scrollbar-thumb {
    background-color: #C0C4CC;
    border-radius: 3px;
}

.data-container::-webkit-scrollbar-track {
    background-color: #f5f7fa;
}

.detail-content {
    height: 500px;
    overflow: hidden;
}

.detail-layout {
    display: flex;
    gap: 24px;
    height: 100%;
}

.table-section {
    flex: 1;
    overflow-y: auto;
    padding-right: 12px;
}

.charts-section {
    width: 500px;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.chart-item {
    flex: 1;
    min-height: 200px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.06);
    padding: 12px;
    width: 100%;
    height: 200px;
}

/* 弹窗样式优化 */
:deep(.detection-dialog) {
    display: flex;
    flex-direction: column;
    margin: 0 !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: 80vh;
}

:deep(.detection-dialog .el-dialog__body) {
    flex: 1;
    overflow: hidden;
    padding: 16px;
}

:deep(.detection-dialog .el-tabs__content) {
    height: calc(100% - 40px);
    overflow: hidden;
}

:deep(.detection-dialog .el-tab-pane) {
    height: 100%;
}

:deep(.el-dialog__header) {
    padding: 16px;
    margin: 0;
    border-bottom: 1px solid #e4e7ed;
}

:deep(.el-dialog__title) {
    font-size: 16px;
    font-weight: 500;
}

:deep(.el-dialog__headerbtn) {
    top: 16px;
}

/* 自定义滚动条样式 */
.table-section::-webkit-scrollbar {
    width: 6px;
}

.table-section::-webkit-scrollbar-thumb {
    background-color: #C0C4CC;
    border-radius: 3px;
}

.table-section::-webkit-scrollbar-track {
    background-color: #f5f7fa;
}

/* 统计区域样式 */
.statistics-section {
    margin-bottom: 12px;
}

.statistics-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;
    margin-top: 10px;
}

.stat-item {
    background-color: #f5f7fa;
    padding: 10px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
}

.stat-item .label {
    color: #606266;
    font-size: 13px;
    margin-bottom: 5px;
}

.stat-item .value {
    color: #303133;
    font-size: 20px;
    font-weight: bold;
}

/* 表格样式 */
:deep(.el-table) {
    font-size: 13px;
}

:deep(.el-table th) {
    padding: 8px 0;
}

:deep(.el-table td) {
    padding: 8px 0;
}
</style>